package cn.icare.cms.controller;

import cn.icare.cms.CouponService;
import cn.icare.cms.ItemCatService;
import cn.icare.cms.MemberCouponService;
import cn.icare.cms.dao.po.Coupon;
import cn.icare.cms.dao.po.MemberCoupon;
import cn.icare.cms.model.enums.CommonStatusEnum;
import cn.icare.cms.model.ro.AddMemberCouponRO;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/personal/coupon")
@Api(tags = "REST优惠券")
public class MemberCouponController extends BaseController {
    @Resource
    private MemberCouponService memberCouponService;
    @Resource
    private CouponService couponService;
    private final String FALL_STRING = "请求失败,服务繁忙!";


    @GetMapping("/alllist")
    @ApiOperation(value = "系统所有可领取优惠券列表", notes = "系统所有可领取优惠券列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, defaultValue = "1", paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, defaultValue = "20", paramType = "query", dataTypeClass = Integer.class)
    })
    public ResponseEntity<RespMsgVO> getList(
            Integer pageNum, Integer pageSize
    ) {
        return super.getRespOk(this.couponService.getCanUseList(pageNum, pageSize));
    }


    @PutMapping("/updatemembercoupon")
    @ApiOperation(value = "会员领取优惠券", notes = "会员领取优惠券")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "优惠券id数组列表", required = true, paramType = "query", dataType = "Integer"
                    , allowMultiple = true
            ),
    })
    public ResponseEntity<RespMsgVO> updateMemberCoupon(Integer[] ids, HttpServletRequest request) {
        Long memberId = this.getCurrentUserId(request);
        boolean isActive = false;
        Integer successNum = 0;
        for (Integer id : ids) {
            isActive = false;

            //每人只限领取一次优惠券，不能重复领取
            if (!this.memberCouponService.exists(memberId, id)) {

                //先判断优惠券状态和剩余领取量
                Coupon coupon = this.couponService.getOne(id);
                if (coupon != null && CommonStatusEnum.EABLED.getCode() == coupon.getStatus()) {
                    if (coupon.getTotal() > coupon.getGettotal()) {
                        isActive = true;
                    }
                }
                if (isActive) {
                    MemberCoupon addMemberCouponRO = new MemberCoupon();
                    addMemberCouponRO.setCouponid(id);
                    addMemberCouponRO.setMemberid(memberId);
                    addMemberCouponRO.setStarttime(coupon.getStarttime());
                    addMemberCouponRO.setEndtime(coupon.getEndtime());
                    Integer result = this.memberCouponService.createOne(addMemberCouponRO);
                    if (result > 0) {
                        //更新优惠券已领用数量
                        Integer getTotal = coupon.getGettotal();
                        getTotal = getTotal + 1;
                        boolean sucess = this.couponService.updateOneGetTotal(id, getTotal);
                        if (sucess) {
                            successNum++;
                        }
                    }
                }
            }
        }
        if (successNum == 0) {
            return super.getRespFail("对不起，优惠券已经领取完");
        } else {
            Map<String,Object> map=new HashMap<>();
            map.put("total",ids.length);
            map.put("success",successNum);
            map.put("msg","优惠券：共"+ids.length+"张，已经成功领取" + successNum + "张");
            return super.getRespOk(map);
        }
    }


    @GetMapping("/mylist")
    @ApiOperation(value = "我的优惠券列表", notes = "我的优惠券列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态：0-已使用 1-未使用 2-过期", required = true, paramType = "query", dataTypeClass = Integer.class),
    })
    public ResponseEntity<RespMsgVO> getList(Integer status,
                                             HttpServletRequest request
    ) {
        Long memberId = this.getCurrentUserId(request);
        return super.getRespOk(this.memberCouponService.getList(memberId, status));
    }


    @GetMapping("/listbyorder")
    @ApiOperation(value = "根据订单金额获取优惠券列表", notes = "根据订单金额获取优惠券列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型：0-不可用 1-可用", required = true, paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "amount", value = "订单金额", required = true, paramType = "query", dataTypeClass = BigDecimal.class),

    })
    public ResponseEntity<RespMsgVO> getListByOrderAmount(Integer type, BigDecimal amount,
                                                          HttpServletRequest request
    ) {
        Long memberId = this.getCurrentUserId(request);
        return super.getRespOk(this.memberCouponService.getListByOrderAmount(memberId, type, amount));
    }


    //#region fallback methods

    //#endregion

}
